/*  GStruct: data structure helpers for Java
 *  Copyright (C) 2011 Giulio Franco
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package gstruct.cli;

import java.util.Iterator;

/**
 * Argument that accepts options, in the form "-argname option"
 * @author Giulio Franco <giulio_franco@msn.com>
 *
 * @param <ResultType> Type of the processed result
 */
public abstract class CLIArgedOption<ResultType> extends CLINoArgOption<ResultType> {
	public static final String MISSING_ARG = "cliarg.error.option.missing_arg";
	
	/**
	 * Creates a CLIArgedOption
	 * @param name	Name of the option (the actual name will hava a dash prefix)
	 * @param description Option description
	 * @param required	Boolean indicating if the option is required
	 * @param unique	Boolean indicating if the option is unique
	 */
	public CLIArgedOption(String name, String description, boolean required,
			boolean unique) {
		super(name, description, required, unique);
	}

	@Override
	public boolean inserted(String matcher, Iterator<String> args,
			ParseResult<? extends ResultType> result) {
		if (super.inserted(matcher, args, result)) {
			if (args.hasNext()) {
				return argumentInserted(args, result, args.next());
			} else {
				result.addError(new ParseError<ResultType>(this, MISSING_ARG));
			}
		}
		return false;
	}
	
	/**
	 * Called upon insertion of the argument
	 * @param args	Iterator pointing to the following arguments
	 * @param result Result object
	 * @param next	Option provided to the argument
	 * @return	True iff the parse can continue
	 */
	protected abstract boolean argumentInserted(Iterator<String> args,
			ParseResult<? extends ResultType> result, String next);
	
	/**
	 * Called at the end of the parse, if the argument was not inserted
	 * Many implementation would implement this method to write a default value
	 * into the result
	 * @param result	Result object
	 * @return	True iff the parse can continue
	 */
	protected abstract boolean argumentNotInserted(
			ParseResult<? extends ResultType> result);
	

	@Override
	public boolean isOk(ParseResult<? extends ResultType> result) {
		if (super.isOk(result)) {
			if (!result.getArguments().contains(this)) {
					return argumentNotInserted(result);
			}
			return true;
		}
		return false;
	}

}
